/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.aip.unit.parser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.unit.exception.UnitError;
import com.baidu.aip.unit.model.AccessToken;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class AccessTokenParser implements Parser<AccessToken> {
	
	private static final Logger logger = LoggerFactory.getLogger(AccessTokenParser.class);
	
    @Override
    public AccessToken parse(String json) throws UnitError {
        try {
        	Gson gson = new GsonBuilder()
            	    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            	    .create();
        	return gson.fromJson(json, AccessToken.class);
        } catch (JsonSyntaxException e) {
        	logger.error("JSON解析失败：{}", e.getMessage());
            UnitError error = new UnitError(UnitError.ErrorCode.JSON_PARSE_ERROR, "Json parse error", e);
            throw error;
        }
    }
}
